package com.cjzuji.rental.dao.impl;


import com.cjzuji.rental.dao.OrderDao;
import com.cjzuji.rental.dao.XWuOrderDao;
import com.cjzuji.rental.mapper.OrderContractMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.mapper.OrderUserMapper;
import com.cjzuji.rental.pojo.Orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class XWuOrderDaoImpl implements XWuOrderDao {
    private static final Logger logger = LoggerFactory.getLogger(XWuOrderDaoImpl.class);
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderUserMapper orderUserMapper;
    @Autowired
    OrderContractMapper orderContractMapper;

    @Override
    //保存数据到订单表
    @Transactional
    public  Long save(Map<String, Object> item,Map<String, Object>  detail,String phone,String assigner) {
        //颜色
        String spec = item.get("spec").toString();
        //logger.info("spec {}",spec);
        String brank = " ";
        String color = " ";
        String suk = " ";
        if (spec != null){
            //分割字符串
            String[] parts = spec.split("\\|");
            for (String part : parts){
                if (part.contains("色")) {
                    color = part;
                   // logger.info("color {}",color);
                } else if (part.contains("G")||part.contains("T")) {
                    suk = part;
                    //logger.info("suk {}",suk);
                }else{
                    brank =brank + part;
                    //logger.info("brank {}",brank);
                }
            }
        }
        //订单状态
        int orderStatus = 7;
        String deliveryNo = " ";
        switch (item.get("order_status").toString()){
            case "104":
                orderStatus = 1;
                break;
            case "105":
                orderStatus = 1;
                break;
            case "130":
                orderStatus = 0;
                break;
            case "116":
                orderStatus = 6;
                break;
            case "106":
                orderStatus = 3;
                break;
            default:
                orderStatus = 7;
                break;
        }
        // 0 待审核  1待发货 2已发货 3租用中 4 逾期 5 已完成  6待支付 7 状态未知
        if (detail.get("receiptExpressInfo") != null){
            Map<String, Object> deliveryList = (Map<String, Object>) detail.get("receiptExpressInfo");
            deliveryNo = deliveryList.get("expressNo").toString();
        }
        Map<String, Object> userOrderInfo = (Map<String, Object>) detail.get("userOrderInfoDto");
        //碎屏险
        Map cashesDto = (Map<String, Object>) detail.get("userOrderCashesDto");
        List<Map<String, Object>> screenRiskList = (List<Map<String, Object>>) detail.get("orderAdditionalServicesDtoList");
        Double screenRisksAmount = 0.0;
        int risksType = 0;
        if (screenRiskList.size() > 0){
            screenRisksAmount = (double) screenRiskList.get(0).get("price");
            if ("1".equals(screenRiskList.get(0).get("status").toString())){
                risksType = 1;
            }
        }
        //租期
        Map<String, Object> productInfo = (Map<String, Object>) detail.get("productInfo");
        Map<String, Object> productDto = (Map<String, Object>) productInfo.get("productDto");
        //身份证上传状态
        int idCardStatus = 0;
        if (userOrderInfo.get("idCardFrontUrl") != null && userOrderInfo.get("idCardFrontUrl") != ""){
            idCardStatus = 1;
        }
        //押金
        Map<String, Object> amountInfoDto = (Map<String, Object>) detail.get("amountInfoDto");
        //分配人

        Orders order = Orders.builder()
                .shopId(5)
                .platformId(9)
                .orderId(item.get("order_id").toString())
                .opinion(userOrderInfo.get("riskLevelZm").toString())  //风控意见
                .assigner(assigner)  //分配人 备注人
                .orderIdTag(item.get("uid").toString()) //平台订单ID
                .carBrand(item.get("name").toString()+brank) //产品备注
                .colour(color)  //商品属性
                .sku(suk)  //商品SKU
                .actualFiancingAmount(Double.parseDouble(cashesDto.get("totalRent").toString()))  //总租金
                .buyoutAmount(Double.parseDouble(cashesDto.get("totalDeposit").toString()) - Double.parseDouble(cashesDto.get("totalRent").toString()))  //买断价 buyoutAmount
                //.discountAmount(discountAmount)   //优惠金额
                .monthRepayment(Double.parseDouble(cashesDto.get("originalRent").toString()))  //月租金
                .bondFreeCreditAmt(Double.parseDouble(cashesDto.get("totalDeposit").toString())) //订单总金额
                .surplusBondAmt((double)amountInfoDto.get("depositAmt")) //押金
                .leaseTerm(productDto.get("rentPeriods").toString())   //订单租期
                .idAuthStatus(idCardStatus)  //身份证上传状态
                .rentStartTime(userOrderInfo.get("rentStart").toString())  //租赁开始时间
                .rentLastTime(userOrderInfo.get("unrentTime").toString())  //租赁结束时间
                .status(orderStatus)    //订单状态
                .deliveryNo(deliveryNo)  //快递单号
                .screenRisksAmount(screenRisksAmount) //碎屏金额   真实支付的碎屏价格
                .screenRisksType(risksType)  //碎屏状态
                .realName(item.get("user_name").toString())  //下单用户
                .phone(phone)  //下单用户手机
                .createTime(userOrderInfo.get("createTime").toString())  // 下单时间
                .updateTime(new Date())
                .build();

        try {
            orderMapper.insert(order);
            return  order.getId();//跟这个写的
        }catch (Exception e){
            logger.info("添加错误" + e.getMessage());
            throw e; // 重新抛出，确保事务回滚
        }
    }

}
